<?php

use think\captcha\Captcha;
use think\Db;

// 异常错误报错级别,
error_reporting(E_ERROR | E_PARSE);

function C($name)
{
    $config = cache('systemConfig');
    if ($config) {
        $value = '';
        foreach ($config as $v) {
            if ($v['name'] == $name) {
                $value = $v['output_value'];
                break;
            }
        }

        return $value;
    } else {
        return Db::name('config')->where(['name' => $name])->order('sort asc')->value('value');
    }
}

/**
 * 系统加密方法
 * @param string $data   要加密的字符串
 * @param int    $expire 过期时间 (单位:秒)
 * @return string
 */
function thinkEncrypt($data, $expire = 0)
{
    $key = md5('083d9a270e6e16b2fbb08d35067aae5f');
    $data = base64_encode($data);
    $x = 0;
    $len = strlen($data);
    $l = strlen($key);
    $char = '';
    for ($i = 0; $i < $len; $i++) {
        if ($x == $l) $x = 0;
        $char .= substr($key, $x, 1);
        $x++;
    }
    $str = sprintf('%010d', $expire ? $expire + time() : 0);
    for ($i = 0; $i < $len; $i++) {
        $str .= chr(ord(substr($data, $i, 1)) + (ord(substr($char, $i, 1))) % 256);
    }

    return str_replace('=', '', base64_encode($str));
}

/**
 * 系统解密方法
 * @param string $data 要解密的字符串 （必须是think_encrypt方法加密的字符串）
 * @return string
 */
function thinkDecrypt($data)
{
    $key = md5('083d9a270e6e16b2fbb08d35067aae5f');
    $x = 0;
    $data = base64_decode($data);
    $expire = substr($data, 0, 10);
    $data = substr($data, 10);
    if ($expire > 0 && $expire < time()) {
        return '';
    }
    $len = strlen($data);
    $l = strlen($key);
    $char = $str = '';
    for ($i = 0; $i < $len; $i++) {
        if ($x == $l) $x = 0;
        $char .= substr($key, $x, 1);
        $x++;
    }
    for ($i = 0; $i < $len; $i++) {
        if (ord(substr($data, $i, 1)) < ord(substr($char, $i, 1))) {
            $str .= chr((ord(substr($data, $i, 1)) + 256) - ord(substr($char, $i, 1)));
        } else {
            $str .= chr(ord(substr($data, $i, 1)) - ord(substr($char, $i, 1)));
        }
    }

    return base64_decode($str);
}

/**
 * 检查验证码
 * */
function checkVerify($code)
{
    $verify = new Captcha();

    return $verify->check($code);
}

/**
 * 判断是否SSL协议
 * @return boolean
 */
function is_ssl()
{
    if (isset($_SERVER['HTTPS']) && ('1' == $_SERVER['HTTPS'] || 'on' == strtolower($_SERVER['HTTPS']))) {
        return true;
    } else if (isset($_SERVER['SERVER_PORT']) && ('443' == $_SERVER['SERVER_PORT'])) {
        return true;
    }

    return false;
}

/**
 * 获取域名前缀
 * */
function getHost()
{
    $res = is_ssl();
    if ($res) {
        return 'https://' . $_SERVER['HTTP_HOST'];
    } else {
        return 'http://' . $_SERVER['HTTP_HOST'];
    }
}

/**
 * 按综合方式输出通信数据
 * @param integer $result 状态码
 * @param string  $msg    提示信息
 * @param array   $data   数据
 * @return string
 */
function apiReturn($result, $msg = '', $data = false)
{
    if (!is_numeric($result)) {
        return '';
    }

    return apiJson($result, $msg, $data);
}

/**
 * 按json方式输出通信数据
 * @param integer $result 状态码
 * @param string  $msg    提示信息
 * @param array   $data   数据
 * @return string
 */
function apiJson($result, $msg = '', $data = false)
{

    if (!is_numeric($result)) {
        return '';
    }

    if ($data > 0 || $data === []) {
        $message = [
            'result' => $result,
            'msg' => $msg,
            'data' => $data ? : []
        ];
    } else {
        $message = [
            'result' => $result,
            'msg' => $msg,
            'data' => $data ? : ''
        ];
    }

    echo json_encode($message, JSON_UNESCAPED_UNICODE);
    exit;
}

/**
 * 根据图片id获取图片路径
 * */
function getPicture($id)
{
    if (preg_replace('/\D/s', '', $id) == $id) {
        //ID
        $info = Db::name('picture')->field('path')->where(['id' => $id])->find();
        if ($info) {
            return getHost() . $info['path'];
        } else {
            return '';
        }
    } else {
        //路径
        return $id;
    }
}

/**
 * 用户头像处理
 * @param int $avatar_id 用户头像ID 或 用户头像路径
 * @return string
 * */
function doAvatar($avatar_id)
{
    if (strlen($avatar_id) < 10) {
        //此时用户头像为修改之后的头像
        $avatar = getPicture($avatar_id);
    } else {
        $avatar = $avatar_id;
    }

    return $avatar ? : '';
}

/**
 * 多图处理
 * @param string $imgs    图片id集合
 * @param string $img_key 自定义图片路径下标
 * @return array
 * */
function doImgs($imgs, $img_key = 'path')
{
    $new_img_arr = [];
    if ($imgs) {
        $img_arr = explode(',', $imgs);

        if ($img_arr) {
            foreach ($img_arr as $k => $v) {
                $new_img_arr[$k]['id'] = $v;
                $new_img_arr[$k][$img_key] = getPicture($v);
            }
        }
    }

    return $new_img_arr;
}

/**
 * 获取[规格-属性]数据
 * @param int $goods_id 商品id
 * @return array
 * */
function getSku($goods_id)
{
    if (!cache('sku_' . $goods_id)) {
        $sku_value_list = Db::name('sku_value')->where(['goods_id' => $goods_id])->select();

        //$skus_id_arr：所有属性的id集合
        $skus_id_arr = [];
        $sku_list = [];
        if ($sku_value_list) {
            foreach ($sku_value_list as &$val) {
                $val['img'] = getPicture($val['img']);

                $sku_id = explode('-', $val['sku_id']);
                if ($sku_id) {
                    foreach ($sku_id as $value) {
                        if (!in_array($value, $skus_id_arr)) {
                            $skus_id_arr[] = $value;
                        }
                    }
                }
            }

            $parent_list = Db::name('sku')->distinct(true)->field('pid')->where(['id' => ['IN', $skus_id_arr]])->select();
            $parent_ids = array_column((array)$parent_list, 'pid');
            if ($parent_ids) {
                $sku_list = Db::name('sku')->field('id,name title')->where(['id' => ['IN', $parent_ids]])->select();
                if ($sku_list) {
                    foreach ($sku_list as &$v) {
                        $child_list = Db::name('sku')->field('id,name title')->where(['pid' => $v['id']])->select();
                        if ($child_list) {
                            foreach ($child_list as &$val) {
                                $val['class'] = '';
                                $val['status'] = false;
                                foreach ($sku_value_list as $value) {
                                    if (in_array($val['id'], explode('-', $value['sku_id'])) && $value['status']) {
                                        $val['status'] = true;
                                        break;
                                    }
                                }
                            }
                        } else {
                            $child_list = [];
                        }
                        $v['child'] = $child_list;
                    }
                } else {
                    $sku_list = [];
                }
            }
        } else {
            $sku_value_list = [];
        }

        $data = [
            'sku_list' => $sku_list,
            'sku_value_list' => $sku_value_list
        ];
        cache('sku_' . $goods_id, $data);
    } else {
        $data = cache('sku_' . $goods_id);
    }

    return $data;
}

/**
 * 微信违规文字检测
 * */
function checkContent($content)
{
    if ($access_token = accessToken()) {
        $checkUrl = 'https://api.weixin.qq.com/wxa/msg_sec_check?access_token=' . $access_token;
        $arr = [
            'content' => $content
        ];

        $result = httpRequest($checkUrl, $arr, 'json');
        $result = json_decode($result, true);

        if ($result['errcode'] != 0) apiReturn(2, '检测到文字含违规内容，请重新编辑');
    } else {
        apiReturn(2, 'access_token获取失败');
    }
}

function accessToken()
{
    $appid = C('XCX_APPID');
    $secret = C('XCX_SECRET');
    $tokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $secret;
    $tokenArr = file_get_contents($tokenUrl);
    $tokenArr = json_decode($tokenArr, true);

    return $tokenArr['access_token'];
}

function httpRequest($url, $data, $type)
{
    if ($type == 'json') {
        $headers = ["Content-type: application/json;charset=UTF-8", "Accept: application/json", "Cache-Control: no-cache", "Pragma: no-cache"];
        $data = json_encode($data, JSON_UNESCAPED_UNICODE);
    } else {
        $headers = [];
    }
    $curl = getCurl($url, $data);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    $output = curl_exec($curl);
    curl_close($curl);

    return $output;
}

/**
 * @param $url
 * @param $data
 * @return false|resource
 */
function getCurl($url, $data = null, $header = null)
{
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
    if (!empty($data)) {
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    }
    // 设置header头
    if (!empty($header)) curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    return $curl;
}

/**
 * 一维数组去重
 * */
function a_array_unique($array)
{
    $out = [];
    foreach ($array as $key => $value) {
        if (!in_array($value, $out)) {
            $out[$key] = $value;
        }
    }

    return $out;
}

/**
 * 处理富文本信息
 * @param string $content 富文本内容
 * @return  string
 * */
function doEditorContent($content)
{
    return $content ? str_replace('<img src="', '<img style="width: 100%; height: auto" src="' . getHost(), $content) : '';
}

/**
 * 格式化时间
 * @param int  $time 时间戳
 * @param date $date 时间格式
 * */
function timeFormat($time, $date = 'Y-m-d H:i:s')
{
    if ($time) {
        return date($date, $time);
    } else {
        return '';
    }
}

/**
 * @param array $sku_id 属性id集合
 * @return string
 * */
function getSkuName($sku_id)
{
    if ($sku_id) {
        $in_sku = implode(',', $sku_id);
        $order = ' field (id, ' . $in_sku . ' ) ';
        $sql = 'SELECT `name` FROM `tp_sku` WHERE `id` IN(' . $in_sku . ') ORDER BY ' . $order;
        return Db::query($sql);
    } else {
        return '';
    }
}

/**
 * 获取省id
 * @param string $province_name 省名称
 * @return int
 * */
function getProvinceId($province_name)
{
    return Db::name('province')->where(['name' => $province_name])->value('province_id');
}

/**
 * 获取省名称
 * @param int $province_id 省id
 * @return string
 * */
function getProvinceName($province_id)
{
    $name = Db::name('province')->where(['province_id' => $province_id])->value('name');

    return $name ? : '';
}

/**
 * 获取市id
 * @param string $province_name 省名称
 * @param string $city_name     市名称
 * @return int
 * */
function getCityId($province_name, $city_name)
{
    $province_id = getProvinceId($province_name);

    $city_name = str_replace(['市', '省'], '', $city_name);
    return Db::name('city')->where(['province_id' => $province_id, 'name' => ['like', $city_name . '%']])->value('city_id');
}

/**
 * 获取市名称
 * @param int $city_id 市id
 * @return string
 * */
function getCityName($city_id)
{
    $name = Db::name('city')->where(['city_id' => $city_id])->value('name');

    return $name ? : '';
}

/**
 * 获取区id
 * @param string $province_name 省名称
 * @param string $city_name     市名称
 * @param string $area_name     市名称
 * @return int
 * */
function getAreaId($province_name, $city_name, $area_name)
{
    $city_id = getCityId($province_name, $city_name);

    $area_name = str_replace(['市', '区', '县'], '', $area_name);
    return Db::name('area')->where(['city_id' => $city_id, 'name' => ['like', $area_name . '%']])->value('area_id');
}

/**
 * 获取区名称
 * @param int $area_id 区id
 * @return string
 * */
function getAreaName($area_id)
{
    $name = Db::name('area')->where(['area_id' => $area_id])->value('name');

    return $name ? : '';
}

function httpsRequest($url, $data = null, $header = null)
{
    $curl = getCurl($url, $data, $header);
    $output = curl_exec($curl);
    curl_close($curl);

    return $output;
}

function get_php_file($filename)
{
    if (!is_file(RUNTIME_PATH . '/' . $filename)) {
        $data['expires_time'] = 0;
        $data['jsapi_ticket'] = '';
        set_php_file($filename, json_encode($data));
    }

    return file_get_contents(RUNTIME_PATH . '/' . $filename);
}

function set_php_file($filename, $content)
{
    file_put_contents(RUNTIME_PATH . '/' . $filename, $content);
}

/**
 * 注册用户 及 绑定用户
 * @param array $user_data 当前用户信息
 * @return array
 * */
function bindUser($user_data)
{
    $time = time();

    $user_info = Db::name('user')->where(['openid' => $user_data['openid']])->find();
    if ($user_info) {
        // 直接返回用户id和用户手机号
        $return_data = [
            'user_id' => $user_info['id'],
            'mobile' => $user_info['mobile'] ? : ''
        ];
    } else {
        // 新用户

        //注册用户信息 及 绑定
        $user_data['create_time'] = $time;

        $return_user_id = Db::name('user')->insertGetId($user_data);

        $return_data = [
            'user_id' => $return_user_id,
            'mobile' => ''
        ];
    }

    return $return_data;
}

/**
 * 生成渠道商发展业务员二维码（用户扫码进入业务员认证页面）
 * @param string $user_id 用户id
 * @return string
 * */
function createChannelQr($user_id)
{
    $channel_qr = Db::name('user')->where(['id' => $user_id])->value('channel_qr');
    if (!$channel_qr) {
        $access_token = getAccessToken();

        $line_color = [
            "r" => "37",
            "g" => "99",
            "b" => "235"
        ];
        $data = [
            'page' => 'pages/salesman_ident/salesman_ident',
            'scene' => (string)$user_id,
            'line_color' => $line_color,
            'env_version' => 'release',// 正式版为 "release"，体验版为 "trial"，开发版为 "develop"
        ];
        $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" . $access_token;

        $img = httpsRequest($url, json_encode($data));

        $dir = './uploads/channelQr/';
        if (!is_dir($dir)) mkdir($dir);

        $path = $dir . 'userQr_' . $user_id . '.png';

        file_put_contents($path, $img);
        $save_path = substr($path, 1);
        Db::name('user')->where(['id' => $user_id])->setField('channel_qr', $save_path);
    }

    return $channel_qr ? (getHost() . $channel_qr) : (getHost() . $save_path);
}

/**
 * 生成业务员发展供应商二维码（用户扫码进入供应商认证页面）
 * @param string $user_id 用户id
 * @return string
 * */
function createSalesmanQr($user_id)
{
    $salesman_qr = Db::name('user')->where(['id' => $user_id])->value('salesman_qr');
    if (!$salesman_qr) {
        $access_token = getAccessToken();

        $data = [
            'page' => 'pages/supplier_channel_ident/supplier_channel_ident',
            'scene' => (string)$user_id,
            'env_version' => 'release',// 正式版为 "release"，体验版为 "trial"，开发版为 "develop"
        ];
        $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" . $access_token;

        $img = httpsRequest($url, json_encode($data));

        $dir = './uploads/salesmanQr/';
        if (!is_dir($dir)) mkdir($dir);

        $path = $dir . 'userQr_' . $user_id . '.png';

        file_put_contents($path, $img);
        $save_path = substr($path, 1);
        Db::name('user')->where(['id' => $user_id])->setField('salesman_qr', $save_path);
    }

    return $salesman_qr ? (getHost() . $salesman_qr) : (getHost() . $save_path);
}

/**
 * 获取access_token
 * @return string
 *  */
function getAccessToken(&$count = 0)
{
    $config = [
        'appid' => C('XCX_APPID'),
        'secret' => C('XCX_SECRET'),
    ];

    // access_token 应该全局存储与更新，以下代码以写入到文件中做示例
    $data = json_decode(get_php_file('access_token.json'));
    if ($data->expires_time < time()) {
        // 如果是企业号用以下URL获取access_token
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $config['appid'] . "&secret=" . $config['secret'];
        $access_token_json = httpsRequest($url);
        $access_token = json_decode($access_token_json, true);
        $code = $access_token['errcode'] ? : 0;
        if ($code == 0) {
            $data->expires_time = time() + 2000;
            $data->access_token = $access_token;
            set_php_file('access_token.json', json_encode($data));

            $access_token = $access_token['access_token'];
        } else {
            if ($count < 3) {
                ++$count;
                getAccessToken($count);
            } else {
                unlink(RUNTIME_PATH . '/access_token.json');
                apiReturn(2, $access_token['errmsg']);
            }
        }
    } else {
        $access_token = $data->access_token->access_token;
    }

    return $access_token;
}

/**
 * 隐藏手机号
 * @param string $tel 手机号
 * @return string
 * */
function hideMobile($tel)
{
    return $tel ? substr_replace($tel, '****', 3, 4) : '';
}

/**
 * 过滤文本中的emoji表情包（输出到excel文件中会导致问题）
 * @param string $text 原文本
 * @return string 过滤emoji表情包后的文本
 */
function removeEmoji($text)
{
    $len = mb_strlen($text);
    $newText = '';
    for ($i = 0; $i < $len; $i++) {
        $str = mb_substr($text, $i, 1, 'utf-8');
        if (strlen($str) >= 4) continue;//emoji表情为4个字节
        $newText .= $str;
    }

    return $newText;
}

/**
 * workerman
 * 获取后台用户列表用户最新的消息时间
 * @param int $user_id 用户id
 * @return string
 * */
function getUserNewMsgTime($user_id)
{
    $create_time = Db::name('chat')
        ->where(['from_uid' => $user_id])
        ->whereOr(
            function ($query) use ($user_id) {
                $query->where(['to_uid' => $user_id]);
            }
        )
        ->order('create_time desc')
        ->value('create_time');

    return $create_time ? date('H:i:s', $create_time) : '';
}

/**
 * 获取用户的真实 IP
 * */
function getRealIp()
{
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    } else {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}

/**
 * 目录清单，列出所有文件和文件夹
 * @param string $dir 路径
 * */
function list_files($dir)
{
    if (is_dir($dir)) {
        if ($handle = opendir($dir)) {
            while (($file = readdir($handle)) !== false) {
                if ($file != "." && $file != ".." && $file != "Thumbs.db"/*pesky windows, images..*/) {
                    echo '<a target="_blank" href="' . $dir . $file . '">' . $file . '</a>' . "\n";
                }
            }
            closedir($handle);
        }
    }
}

/**
 * 删除文件夹内容
 * @param string $path 路径
 * */
function Delete($path)
{
    if (is_dir($path) === true) {
        $files = array_diff(scandir($path), ['.', '..']);
        foreach ($files as $file) {
            Delete(realpath($path) . '/' . $file);
        }
        return rmdir($path);
    } else if (is_file($path) === true) {
        return unlink($path);
    }
    return false;
}

/**
 * 计算两个地图坐标之间的距离
 * */
function getDistanceBetweenPointsNew($latitude1, $longitude1, $latitude2, $longitude2)
{
    $theta = $longitude1 - $longitude2;
    $miles = (sin(deg2rad($latitude1)) * sin(deg2rad($latitude2))) + (cos(deg2rad($latitude1)) * cos(deg2rad($latitude2)) * cos(deg2rad($theta)));
    $miles = acos($miles);
    $miles = rad2deg($miles);
    $miles = $miles * 60 * 1.1515;
    $feet = $miles * 5280;
    $yards = $feet / 3;
    $kilometers = $miles * 1.609344;
    $meters = $kilometers * 1000;
    return compact('miles', 'feet', 'yards', 'kilometers', 'meters');
}

/**
 * 转换字节
 * @param int $bytes 传入字节数值
 * @param int $decimals
 * @return string BKMGTP
 */
function human_filesize($bytes, $decimals = 2)
{
    $sz = 'BKMGTP';
    $factor = floor((strlen($bytes) - 1) / 3);
    return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . @$sz[$factor];
}

/**
 * 删除该目录以及该目录下面的所有文件和文件夹
 * @param string $dir 目录
 * @return bool
 */
function removeDir($dirName)
{
    //判断传入参数是否目录，如不是执行删除文件
    if (!is_dir($dirName)) {
        //删除文件
        @unlink($dirName);
    }
    //如果传入是目录，使用@opendir将该目录打开，将返回的句柄赋值给$handle
    $handle = @opendir($dirName);
    //这里明确地测试返回值是否全等于（值和类型都相同）FALSE
    //否则任何目录项的名称求值为 FALSE 的都会导致循环停止（例如一个目录名为“0”）
    while (($file = @readdir($handle)) !== false) {
        //在文件结构中，都会包含形如“.”和“..”的向上结构
        //但是它们不是文件或者文件夹
        if ($file != '.' && $file != '..') {
            //当前文件$dir为文件目录+文件
            $dir = $dirName . '/' . $file;
            //判断$dir是否为目录，如果是目录则递归调用reMoveDir($dirName)函数
            //将其中的文件和目录都删除；如果不是目录，则删除该文件
            is_dir($dir) ? removeDir($dir) : @unlink($dir);
        }
    }
    closedir($handle);
    return rmdir($dirName);
}

/**
 * 提现状态
 * */
function doWithdrawalStatus($status)
{
    switch ($status) {
        case 1:
            $desc = '审核通过';
            break;
        case 2:
            $desc = '审核驳回';
            break;
        case 3:
            $desc = '已打款';
            break;
        default:
            $desc = '待审核';
            break;
    }
    return $desc;
}

function doUserLevel($level)
{
    $user_level = array_values(array_filter(C('USER_LEVEL')));
    return $user_level[$level - 1];
}


/**
 * 积分变动
 * @param int    $user_id    用户id
 * @param int    $integral   积分
 * @param string $type       类型
 * @param int    $link_id    关联id
 * @param string $link_table 关联表（全名）
 * @return boolean
 * */
function doIntegral($user_id, $integral, $type, $link_id = 0, $link_table = '', $remark = '')
{
    $user_info = Db::name('user')->where(['id' => $user_id])->find();
    Db::startTrans();
    try {
        $time = time();
        $abs_integral = abs($integral);

        if ($integral > 0) {
            $user_data = [
                'all_integral' => $user_info['all_integral'] + $integral,
                'integral' => $user_info['integral'] + $integral
            ];
            $res = Db::name('user')->where(['id' => $user_id])->update($user_data);
        } else {
            $user_data = [
                'all_integral' => $user_info['all_integral'] - $abs_integral,
                'integral' => $user_info['integral'] - $abs_integral
            ];
            $res = Db::name('user')->where(['id' => $user_id])->update($user_data);
        }

        if (!$res) {
            Db::rollback();
            return false;
        }

        $data = [
            'user_id' => $user_id,
            'integral' => $abs_integral,
            'before' => $user_info['integral'],// 变动前
            'after' => $user_info['integral'] + $integral,// 变动后
            'type' => $type,
            'remark' => $remark,
            'link_id' => $link_id,
            'link_table' => $link_table,
            'create_time' => $time,
        ];
        Db::name('user_integral_log')->insert($data);

        Db::commit();
        return true;
    } catch (\Exception $e) {
        Db::rollback();
        return false;
    }
}

/**
 * 评分变动
 * @param int    $user_id     用户id
 * @param int    $ident_id    认证id
 * @param string $score_field 评分字段名
 * @param int    $score       评分
 * @param string $type        类型
 * @param int    $link_id     关联id
 * @param string $link_table  关联表（全名）
 * @return boolean
 * */
function doScore($user_id, $ident_id, $score_field, $score, $type, $link_id = 0, $link_table = '', $remark = '')
{
    $user_info = Db::name('user')->where(['id' => $user_id])->find();
    Db::startTrans();
    try {
        $time = time();
        $abs_score = abs($score);

        if ($score > 0) {
            $res = Db::name('user')->where(['id' => $user_id])->setInc($score_field, $score);
        } else {
            $res = Db::name('user')->where(['id' => $user_id])->setDec($score_field, $abs_score);
        }

        if (!$res) {
            Db::rollback();
            return false;
        }

        $data = [
            'user_id' => $user_id,
            'ident_id' => $ident_id,
            'score' => $score,
            'before' => $user_info[$score_field],// 变动前
            'after' => $user_info[$score_field] + $score,// 变动后
            'type' => $type,
            'remark' => $remark,
            'link_id' => $link_id,
            'link_table' => $link_table,
            'create_time' => $time,
        ];
        Db::name('user_score_log')->insert($data);

        Db::commit();
        return true;
    } catch (\Exception $e) {
        Db::rollback();
        return false;
    }
}

/**
 * 格式化时间戳为相对时间描述
 * @param int|string $timestamp 时间戳或可转换的时间字符串
 * @return string 格式化后的时间描述
 */
function formatRelativeTime($timestamp)
{
    if (!is_numeric($timestamp)) {
        $timestamp = strtotime($timestamp);
    }

    $now = time();
    $diff = $now - $timestamp;

    if ($diff < 60) {
        return '刚刚';
    } elseif ($diff < 3600) {
        $minutes = floor($diff / 60);
        return $minutes . '分钟前';
    } elseif ($diff < 86400) {
        $hours = floor($diff / 3600);
        return $hours . '小时前';
    } elseif ($diff < 259200) { // 3 天内
        $days = floor($diff / 86400);
        return $days . '天前';
    } else {
        return date('Y-m-d', $timestamp);
    }
}

/**
 * 积分类型
 * */
function doIntegralTypeDesc($type)
{
    switch ($type) {
        case 'share_register':
            $desc = '业务员拉新奖励';
            break;
        case 'admin_post':
            $desc = '后台操作';
            break;
        default:
            $desc = '';
            break;
    }
    return $desc;
}

/**
 * 积分类型
 * */
function doScoreTypeDesc($type)
{
    switch ($type) {
        case 'share_register':
            $desc = '业务员拉新奖励';
            break;
        case 'comment':
            $desc = '供应商评分';
            break;
        case 'admin_post':
            $desc = '后台操作';
            break;
        default:
            $desc = '';
            break;
    }
    return $desc;
}

/**
 * 订单状态
 * */
function doOrderStatus($status)
{
    switch ($status) {
        case 1:
            $desc = '申请中';
            break;
        case 2:
            $desc = '服务中';
            break;
        case 3:
            $desc = '已完成';
            break;
    }
    return $desc ? : '';
}

/**
 * 评分描述
 * */
function doScoreDesc($score)
{
    switch ($score) {
        case -1:
            $desc = '不满意';
            break;
        case 1:
            $desc = '一般';
            break;
        case 2:
            $desc = '满意';
            break;
        case 3:
            $desc = '非常满意';
            break;
    }
    return $desc ? : '';
}

/**
 * openid换取用户ID
 * */
function openidGetUserId($openid)
{
    if ($openid) {
        $user_id = Db::name('user')->where(['openid' => $openid])->value('id');
    }

    return $user_id ? : 0;
}


/*
 * 获取用户绑定关系数据
 * @param int $share_user_id 分享人用户id
 * @param int $style 1：渠道商发展业务员， 2：业务员发展供应商
 * @return array
 * */
function bindUserUp($share_user_id, $style = 1)
{
    $data = [];
    if ($share_user_id) {
        if ($style == 1) {
            // 查询渠道商信息
            $channel_user_info = Db::name('user')->field('id,channel_id')->where(['id' => $share_user_id])->find();
            $channel_status = Db::name('user_ident')->where(['id' => $channel_user_info['channel_id']])->value('status');
            if ($channel_status == 1) {
                // 渠道商发展业务员
                $data['up_channel_user_id'] = $share_user_id;
            }
        } elseif ($style == 2) {
            // 查询业务员信息
            $salesman_user_info = Db::name('user')->field('id,up_channel_user_id,salesman_id,salesman_score')->where(['id' => $share_user_id])->find();
            $salesman_status = Db::name('user_ident')->where(['id' => $salesman_user_info['salesman_id']])->value('status');
            if ($salesman_status == 1) {
                // 业务员发展供应商
                $data['up_salesman_user_id'] = $share_user_id;
            }
        }
    }
    return $data ? : [];
}

/**
 * 解析HTML表格为结构化数组
 * @param string $html
 * @return array
 */
function parseHtmlTableToArray($html)
{
    $dom = new DOMDocument();
    libxml_use_internal_errors(true); // 忽略 HTML 错误
    $dom->loadHTML('<?xml encoding="utf-8" ?>' . $html);
    libxml_clear_errors();

    $result = [];

    // 获取所有 tr
    $rows = $dom->getElementsByTagName('tr');

    foreach ($rows as $row) {
        $tds = $row->getElementsByTagName('td');
        $tdCount = $tds->length;

        // 一般是每两个td为一组（label + value）
        for ($i = 0; $i < $tdCount - 1; $i += 2) {
            $labelNode = $tds->item($i);
            $valueNode = $tds->item($i + 1);

            $label = trim(strip_tags($labelNode->textContent));
            $value = trim(strip_tags($valueNode->textContent));

            if ($label || $value) {
                $result[] = [
                    'label' => $label,
                    'value' => $value,
                ];
            }
        }
    }

    return $result;
}

function doQuoteUnit($quoteUnit)
{
    switch ($quoteUnit) {
        case 'YUAN_KG':
            $quoteUnit = '元/千克';
            break;
        case 'YUAN_T':
            $quoteUnit = '元/吨';
            break;
        case 'YUAN_MU':
            $quoteUnit = '元/亩';
            break;
        default:
            $quoteUnit = '';
    }
    return $quoteUnit;
}

/**
 * 将富文本内容转换为适合微信小程序显示的格式（优化表格处理）
 * @param string $html 富文本HTML内容
 * @return string 转换后的小程序显示内容
 */
function formatRichTextForWechatMiniProgram($html)
{
    $html = preg_replace('/<style\b[^>]*>.*?<\/style>/is', '', $html);

    // 1. 预处理：移除不需要的属性和样式
    $html = preg_replace('/<([a-z][a-z0-9]*)[^>]*?(\/?)>/i', '<$1$2>', $html);
    $html = preg_replace('/style="[^"]*"/', '', $html);
    $html = preg_replace('/class="[^"]*"/', '', $html);
    $html = preg_replace('/data-v-[a-z0-9]+/', '', $html);

    // 2. 处理特殊标签
    $html = str_replace(['<o:p>', '</o:p>'], '', $html);
    $html = str_replace('<p class="MsoNormal">', '<p>', $html);
    $html = str_replace('<p class="MsoPlainText">', '<p>', $html);
    $html = str_replace(['<span>', '</span>'], '', $html);
    $html = str_replace(['<font face="宋体">', '</font>'], '', $html);

    // 3. 特别处理表格 - 保留结构并添加小程序专用class
    $html = preg_replace_callback('/<table[^>]*>(.*?)<\/table>/is', function ($matches) {
        $tableContent = $matches[1];

        // 处理表头（如果有）
        $tableContent = preg_replace('/<thead>(.*?)<\/thead>/is', '<thead>$1</thead>', $tableContent);

        // 处理表体
        $tableContent = preg_replace('/<tbody>(.*?)<\/tbody>/is', '<tbody>$1</tbody>', $tableContent);

        // 处理行
        $tableContent = preg_replace_callback('/<tr[^>]*>(.*?)<\/tr>/is', function ($trMatches) {
            $rowContent = $trMatches[1];

            // 处理单元格
            $rowContent = preg_replace_callback('/<(td|th)[^>]*>(.*?)<\/(td|th)>/is', function ($cellMatches) {
                $cellType = strtolower($cellMatches[1]);
                $cellContent = $cellMatches[2];

                // 清理单元格内容
                $cellContent = preg_replace('/<[^>]+>/', '', $cellContent);
                $cellContent = trim($cellContent);

                // 添加小程序class
                $cellClass = ($cellType === 'th') ? 'wx-table-th' : 'wx-table-td';

                return "<{$cellType} class='{$cellClass}'>{$cellContent}</{$cellType}>";
            },                                  $rowContent);

            return "<tr class='wx-table-tr'>{$rowContent}</tr>";
        },                                    $tableContent);

        return "<table class='wx-table'>{$tableContent}</table>";
    },                            $html);

    // 4. 处理其他文本格式
    $html = preg_replace('/text-align:\s*center;/i', 'class="text-center"', $html);
    $html = preg_replace('/text-align:\s*right;/i', 'class="text-right"', $html);
    $html = preg_replace('/text-indent:\s*\d+pt;/i', '', $html);

    // 5. 处理换行
    //    $html = str_replace(['<br>', '<br/>', '<br />'], PHP_EOL, $html);

    // 6. 添加小程序样式类
    $html = str_replace('<p>', '<p class="wx-rich-text-p">', $html);
    $html = str_replace('<b>', '<b class="wx-rich-text-bold">', $html);
    $html = str_replace('<i>', '<i class="wx-rich-text-italic">', $html);

    // 7. 最终清理
    $html = preg_replace('/\s+/', ' ', $html);
    $html = preg_replace('/> </', '><', $html);
    $html = strip_tags($html, '<p><b><i><div><a><img><span><strong><em><u><br><table><thead><tbody><tr><td><th>');

    return $html;
}

function doSalesmanLevel($score)
{
    $salesman_level = array_reverse(array_values(array_filter(C('SALESMAN_LEVEL'))));
    $level = '';
    foreach ($salesman_level as $v) {
        // 字符串转按照：数组
        $arr = explode('：', $v);
        if ($score >= $arr[0]) {
            $level = $arr[1];
            break;
        }
    }
    return $level;

}